<template>
  <div class="my-course-container p-4">
    <!-- 操作按钮区域 -->
    <div class="mb-4 flex flex-wrap gap-2 items-center">
      <el-select
        v-model="selectedRoundId"
        placeholder="请选择轮次"
        clearable
        style="width: 200px"
        @change="fetchMyCourses"
      >
        <el-option
          v-for="item in roundOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </div>

    <!-- 课程卡片区域 -->
    <div v-if="loading" class="flex justify-center items-center py-8">
      <el-skeleton :rows="3" animated />
    </div>

    <div v-else-if="myCourses.length === 0" class="empty-state">
      <el-empty description="暂无选课记录" />
    </div>

    <div v-else class="course-cards-container">
      <el-card
        v-for="course in myCourses"
        :key="course.id"
        class="course-card mb-4"
        shadow="hover"
      >
        <div class="flex justify-between items-start">
          <div>
            <h3 class="text-lg font-bold mb-2">{{ course.courseName }}</h3>
            <div class="text-gray-600 mb-1">
              <span class="mr-2">轮次: {{ roundName }}</span>
              <span>授课教师: {{ course.teacherName }}</span>
            </div>
            <div class="text-gray-600 mb-1">
              <span class="mr-2"
                >选课人数: {{ getCoursePerson(course.tcdId) }}/{{
                  getCoursePersonMax(course.tcdId)
                }}</span
              >
            </div>
          </div>
          <div class="flex space-x-2">
            <el-button
              type="primary"
              size="small"
              plain
              @click="handleDetail(course)"
            >
              详细
            </el-button>
            <el-button
              type="danger"
              size="small"
              plain
              @click="handleQuit(course)"
            >
              退课
            </el-button>
          </div>
        </div>
      </el-card>

    </div>

    <!-- 详情对话框 -->
    <el-dialog title="课程详情" v-model="detailDialogVisible" width="600px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="选课ID">{{
          courseDetail.tcdId
        }}</el-descriptions-item>
        <el-descriptions-item label="轮次">{{
          roundName
        }}</el-descriptions-item>
        <el-descriptions-item label="课程">{{
          courseDetail.courseName
        }}</el-descriptions-item>
        <el-descriptions-item label="授课教师">{{
          courseDetail.teacherName
        }}</el-descriptions-item>
        <el-descriptions-item label="当前选课人数">{{
          getCoursePerson(courseDetail.tcdId)
        }}</el-descriptions-item>
        <el-descriptions-item label="最大选课人数">{{
          getCoursePersonMax(courseDetail.tcdId)
        }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{
          formatDateTime(courseDetail.createTime)
        }}</el-descriptions-item>
        <el-descriptions-item label="更新时间" :span="2">{{
          formatDateTime(courseDetail.updateTime)
        }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
// 轮次
import { getroundlist } from '@/api/round'
// 用户
import { userlist } from '@/api/usersManage'
// 我的选课
import {
  getcourseselection,
  deletecourseselection,
} from '@/api/courseSelection'
// 用户
import { useUserStore } from '@/stores/user.js'
// 课程详情
import { getcourseDetails } from '@/api/courseDetails.js'


const userStore = useUserStore()

// 轮次选项
const roundOptions = ref([])
const selectedRoundId = ref('')

// 根据rountdId显示轮询名称
const roundName = computed(() => {
  return roundOptions.value.find((item) => item.value === selectedRoundId.value)
    ?.label
})

// 我的课程数据
const myCourses = ref([])
const loading = ref(false)

// 用户列表
const userList = ref([])

// 课程列表
const courseList = ref([])

// 详情对话框
const detailDialogVisible = ref(false)
const courseDetail = reactive({
  id: '',
  roundId: '',
  courseId: '',
  userId: '',
  personMax: 0,
  chooseNum: 0,
  courseName: '',
  username: '',
  createTime: '',
  updateTime: '',
})

// 格式化日期时间
const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return ''
  return dateTimeString.replace('T', ' ').replace(/\.000Z$/, '')
}

// 获取轮次列表
const getRoundList = async () => {
  try {
    const { code, data, msg } = await getroundlist({
      pageNum: 1,
      pageSize: 10,
    })
    if (code !== 200) {
      throw new Error(msg)
    }
    roundOptions.value = data.records.map((item) => ({
      value: item.id,
      label: item.name,
    }))

    // 如果有轮次数据，默认选择第一个
    if (roundOptions.value.length > 0) {
      selectedRoundId.value = roundOptions.value[0].value
      fetchMyCourses()
    }
  } catch (error) {
    ElMessage.error(error.message || '获取轮次数据失败')
  }
}

// 获取用户列表
const getUserList = async () => {
  try {
    const { code, data, msg } = await userlist()
    if (code !== 200) {
      throw new Error(msg)
    }
    userList.value = data.records
  } catch (error) {
    ElMessage.error(error.message || '获取用户列表失败')
  }
}

// 根据用户id获取用户名称
const getUserName = (userId) => {
  return userList.value.find((item) => item.id === userId)?.username
}

// 获取课程列表
const getCourseList = async () => {
  try {
    const { code, data, msg } = await getcourseDetails()
    if (code !== 200) {
      throw new Error(msg)
    }
    courseList.value = data.records || []
  } catch (error) {
    ElMessage.error(error.message || '获取课程列表失败')
  }
}

// 根据课程id获取课程人数
const getCoursePerson = (courseId) => {
  return courseList.value.find((item) => item.id === courseId)?.chooseNum
}

// 根据课程id获取课程最大人数
const getCoursePersonMax = (courseId) => {
  return courseList.value.find((item) => item.id === courseId)?.personMax
}

// 获取我的选课列表
const fetchMyCourses = async () => {
  if (!selectedRoundId.value) {
    myCourses.value = []
    return
  }

  loading.value = true
  try {
    const { code, data, msg } = await getcourseselection(selectedRoundId.value)
    if (code !== 200) {
      throw new Error(msg)
    }
    myCourses.value = data || []
  } catch (error) {
    ElMessage.error(error.message || '获取我的课程失败')
    myCourses.value = []
  } finally {
    loading.value = false
  }
}

// 处理退课
/**
 * 处理退课操作
 * @param {Object} course - 课程对象
 */
const handleQuit = async (course) => {
  try {
    // 显示确认对话框
    await ElMessageBox.confirm(
      `确定要退出课程"${course.courseName}"吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    // 用户确认后执行退课操作
    const { code, msg } = await deletecourseselection({
      roundId: course.roundId,
      tcdId: course.tcdId,
      userId: userStore.userInfo.id,
    })

    if (code !== 200) {
      throw new Error(msg)
    }

    ElMessage.success('退课成功')
    fetchMyCourses() // 刷新课程列表
  } catch (error) {
    // 如果是用户取消操作，不显示错误信息
    if (error !== 'cancel' && error !== 'close') {
      ElMessage.error(error.message || '退课失败')
    }
  }
}

// 处理查看详情
const handleDetail = (row) => {
  Object.assign(courseDetail, row)
  detailDialogVisible.value = true
}

onMounted(() => {
  // 获取轮次数据
  getRoundList()
  // 获取用户列表
  getUserList()
  // 获取课程列表
  getCourseList()
})
</script>

<style lang="less" scoped>
.my-course-container {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  min-height: calc(100vh - 140px);
}

.course-cards-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
}

.course-card {
  transition: all 0.3s;

  &:hover {
    transform: translateY(-5px);
  }
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}
</style>
